<template>
  <div>
    <van-popup v-model="isShow" @close="popupClose">
      <div v-if="!resultBase64" class="share-wrapper">
        <div id="share-product">
          <div class="detail">
            <div class="title">
              <p>
                <img
                  v-if="Number(shareObj.crossBorderProduct)"
                  class="tag-haitao"
                  :src="icon.tagHaitao"
                />
                <img
                  v-if="
                    shareObj.productLabelMap &&
                      shareObj.productLabelMap.realSelfBusiness === 1
                  "
                  class="tag-dapai"
                  :src="icon.tagDapai"
                />
                <span>{{ shareObj.title }}</span>
              </p>
            </div>
            <div class="info">
              <div class="price">
                <div class="cur-price"><span>¥</span>{{ shareObj.price }}</div>
                <div v-if="isShowTagPrice" class="tag-price">
                  <div class="fake-line"></div>
                  <span>{{ shareObj.tagPrice }}</span>
                </div>
              </div>
              <div class="tips">
                <span v-if="isShowTagPrice">{{
                  shareObj.tips && shareObj.tips.length && shareObj.tips[0]
                }}</span>
                <span
                  v-if="shareObj.isCombination && shareObj.combinationNum"
                  >{{ `${shareObj.combinationNum}件一组` }}</span
                >
                <span v-if="overseaType">{{ overseaType }}</span>
              </div>
            </div>
            <div class="desc-wrap">
              <div v-if="desList.length > 0">
                <p v-for="(item, index) in desList" :key="index">{{ item }}</p>
              </div>
              <p v-if="shareObj.boHaoName && shareObj.boHao">
                {{ shareObj.boHaoName }} {{ shareObj.boHao }}
              </p>
            </div>
          </div>
          <div class="img-wrap">
            <img :src="imgUrlObj" class="big-img" />
            <div class="small-img-wrap">
              <img v-if="imgUrlObj1" :src="imgUrlObj1" class="small-img" />
              <img v-if="imgUrlObj2" :src="imgUrlObj2" class="small-img" />
              <img v-if="imgUrlObj3" :src="imgUrlObj3" class="small-img" />
            </div>
          </div>
          <div v-if="shareObj.scheduleType === 3" class="store-tips">
            价格以实际购买为准
          </div>
          <div
            class="bottom-wrap"
            :class="{ mt0: shareObj.scheduleType === 3 }"
          >
            <img class="qrcode" :src="qrcode" />
            <div class="store-info">
              <span class="store-name">{{ shopName }}</span>
              <span v-if="shareObj.nickname" class="store-nickname">{{
                shareObj.nickname
              }}</span>
              <span class="qrcode-tip">长按识别或扫码，进入购买</span>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
    <van-loading v-show="loading" color="white" class="loading" />
    <img
      v-if="getHostEnvironment() === 'wechat' && isShow && !this.loading"
      :src="resultBase64"
      class="result no-select"
    />
    <div
      v-if="getHostEnvironment() === 'browser' && isShow && !this.loading"
      class="result result-browser"
    >
      <span>长按图片，保存至手机，方便分享和再次浏览 </span>
      <img :src="resultBase64" />
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode';
import html2canvas from '@/utils/html2canvas.esm';
import {
  formatImgForCanvas,
  getScrollY,
  savePicToLocal,
  getHostEnvironment
} from '@/utils/util';
import shareCardMixin from '@/mixins/shareCardMixin';
import tagHaitao from '@/assets/promotion/haitao/tag-haitao2713.png';
import tagDapai from '@/assets/promotion/dapaiqingcang/icon_dapai_58x16@2x.png';

export default {
  mixins: [shareCardMixin],
  props: {
    shareObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      qrcode: null,
      isShow: false,
      resultBase64: null,
      imgUrlObj: '',
      imgUrlObj1: '',
      imgUrlObj2: '',
      imgUrlObj3: '',
      brandLogoUrlObj: {},
      newImgUrls: [],
      icon: {
        tagHaitao,
        tagDapai
      }
    };
  },
  computed: {
    desList() {
      return this.shareObj.desc ? this.shareObj.desc.split('\n') : [];
    },
    shopName() {
      let { shopName } = this.shareObj;
      if (shopName && shopName.length > 15) {
        shopName = `${shopName.slice(0, 15)}...`;
      }
      return shopName;
    },
    isShowTagPrice() {
      const { price = 0, tagPrice = 0 } = this.shareObj;
      if (price && tagPrice) {
        return Number(tagPrice) >= Number(price);
      }
      return false;
    },
    overseaType() {
      const { overseaType } = this.shareObj;
      let str = '';
      switch (overseaType) {
        case '1':
          str = '海外直邮';
          break;
        case '2':
          str = '保税仓发货';
          break;
        default:
      }
      return str;
    }
  },
  watch: {
    // shareObj(newVal) {
    //   // 没有底图,显示老海报
    //   if (!newVal.shareFloorImgUrl && newVal && newVal.link) {
    //     this.create();
    //   }
    // },
    isShow(newVal) {
      if (!newVal) {
        this.loading = false;
        this.resultBase64 = null;
      } else {
        this.loading = true;
        this.create();
      }
    }
  },
  methods: {
    getHostEnvironment,
    async create() {
      this.resetZoom();
      try {
        this.imgUrlObj = await formatImgForCanvas(
          this.shareObj.pictureUrls[0],
          300,
          300
        );
        if (this.shareObj.pictureUrls.length >= 2) {
          this.imgUrlObj1 = await formatImgForCanvas(
            this.shareObj.pictureUrls[1],
            109,
            109
          );
        }
        if (this.shareObj.pictureUrls.length >= 3) {
          this.imgUrlObj2 = await formatImgForCanvas(
            this.shareObj.pictureUrls[2],
            109,
            109
          );
        }
        if (this.shareObj.pictureUrls.length >= 4) {
          this.imgUrlObj3 = await formatImgForCanvas(
            this.shareObj.pictureUrls[3],
            109,
            109
          );
        }
      } catch (e) {
        console.log(e);
      }
      QRCode.toDataURL(this.shareObj.link, { margin: 1 }).then(url => {
        this.qrcode = url;
        this.$nextTick(() => {
          const source = document.getElementById('share-product');
          if (!source) {
            return;
          }
          const rect = source.getBoundingClientRect();
          const coptDom = source.cloneNode(true);
          coptDom.style.zIndex = -1;
          coptDom.style.width = `${rect.width}px`;
          coptDom.style.height = `${rect.height}px`;
          document.body.appendChild(coptDom);

          // 适配iOS 13, 12 及以下 && 安卓
          const scrollY = getScrollY();
          console.log('==海报==', rect, scrollY);
          html2canvas(coptDom, {
            allowTaint: true,
            useCORS: true,
            logger: true,
            x: rect.left,
            y: rect.top + scrollY,
            scale: 1.6
          })
            .then(canvas => {
              let imgUri = canvas.toDataURL();
              // imgUri = null;
              this.resultBase64 = imgUri;
              this.loading = false;
              document.body.removeChild(coptDom);
            })
            .catch(err => {
              this.loading = false;
              document.body.removeChild(coptDom);
              console.log(err);
            });
        });
      });
    },
    savePicture() {
      savePicToLocal(this.resultBase64, this.shareObj.brandName);
    }
  }
};
</script>

<style scoped>
.van-popup {
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: transparent;
  z-index: 9999;
}

.bg-transparent {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
</style>

<style lang="scss" scoped>
.share-wrapper {
  width: 375px;
  position: relative;
}
#share-product {
  font-family: PingFang-SC-Medium;
  width: 375px;
  top: 50%;
  left: 50%;
  background: #fff;
  transform: translate(-50%, -50%);
  position: fixed;
  .detail {
    padding: 16px 0 0 16px;
    .title {
      display: flex;
      align-items: center;
      margin-bottom: 2px;
      p {
        flex: 1;
        color: #333333;
        font-size: 18px;
        font-family: PingFangSC-Medium;
        font-weight: 500;
        line-height: 25px;

        .tag-haitao {
          margin-right: 3px;
          display: inline-block;
          width: 32px;
          height: 16px;
          vertical-align: middle;
        }
        .tag-dapai {
          margin-right: 3px;
          display: inline-block;
          width: 58px;
          height: 16px;
          vertical-align: middle;
        }
      }
      img {
        width: 40px;
        height: 40px;
        margin-right: 10px;
      }
    }
    .info {
      display: flex;
      align-items: baseline;
      margin-bottom: 6px;
      .price {
        display: flex;
        align-items: baseline;
        margin-right: 12px;

        .cur-price {
          margin-right: 4px;
          color: #ff2a31;
          font-size: 26px;
          font-family: PingFangSC-Semibold;
          font-weight: 600;
          span {
            font-size: 14px;
            margin-right: 4px;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            color: #ff3037;
          }
        }
        .tag-price {
          font-size: 12px;
          color: #999;
          /*text-decoration: line-through;*/
          font-family: PingFangSC-Regular;
          position: relative;
          .fake-line {
            position: absolute;
            width: 100%;
            height: 1px;
            background: #9b9b9b;
            left: 0;
            top: 50%;
          }
        }
      }
      .tips {
        color: #ff2a31;
        font-size: 12px;
        display: flex;
        align-items: center;
        span {
          padding: 2px 8px;
          border-radius: 2px;
          background: rgba(255, 42, 49, 0.08);
          font-family: PingFangSC-Medium;
          font-weight: 500;
          margin-right: 4px;
          /*line-height: 12px;*/
          /*height: 20px;*/
        }
      }
    }
  }
  .desc-wrap {
    p {
      font-size: 13px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(85, 85, 85, 1);
      line-height: 18px;
      word-wrap: break-word;
      word-break: break-all;
    }
    margin-bottom: 8px;
  }
  .img-wrap {
    width: 343px;
    margin: 0 auto;
    .big-img {
      width: 343px;
      height: 343px;
      margin-bottom: 8px;
    }
    .small-img-wrap {
      width: 100%;
      display: flex;
    }
    .small-img {
      width: 109px;
      height: 109px;
      margin-right: 8px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
  .store-tips {
    font-size: 11px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(153, 153, 153, 1);
    line-height: 16px;
    text-align: right;
    padding-right: 16px;
  }
  .bottom-wrap {
    width: 343px;
    margin: 13px auto 21px;
    display: flex;
    align-items: center;
    &.mt0 {
      margin-top: 0;
    }
    .qrcode {
      width: 84px;
      height: 84px;
      margin-right: 10px;
    }
    .store-info {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      .store-name {
        font-size: 16px;
        font-family: PingFangSC-Semibold;
        font-weight: 600;
        color: rgba(51, 51, 51, 1);
        line-height: 22px;
        word-wrap: break-word;
      }
      .store-nickname {
        font-size: 13px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: rgba(51, 51, 51, 1);
        line-height: 18px;
        margin-top: 3px;
      }
      .qrcode-tip {
        font-size: 13px;
        font-family: PingFangSC-Regular;
        font-weight: 400;
        color: #999;
        line-height: 18px;
        margin-top: 7px;
      }
    }
  }
}
.loading {
  z-index: 9999;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.result {
  top: 50%;
  left: 50%;
  position: fixed;
  height: 86%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  span {
    color: #ffffff;
    font-size: 14px;
    margin-bottom: 8px;
  }
  &.no-select {
    -webkit-touch-callout: none; /*系统默认菜单被禁用*/
    user-select: none; //文本不能被选择
  }
  img {
    border-radius: 8px;
    height: 100%;
  }
}

.result-browser {
  width: 80%;

  img {
    width: 100%;
  }
}
</style>
